package br.com.j7.jdesk.persistence.repository.impl;

import java.util.List;

import br.com.j7.jdesk.library.exception.RepositoryException;
import br.com.j7.jdesk.persistence.entity.Enterprises;
import br.com.j7.jdesk.persistence.entity.Users;
import br.com.j7.jdesk.persistence.entity.UsersGroups;
import br.com.j7.jdesk.persistence.repository.EnterpriseRepository;

/**
 * 
 * 
 * @author Edivando Alves
 *
 */
public class EnterpriseRepositoryImpl extends AbstractRepository<Enterprises> implements EnterpriseRepository{
	

	/*
	 * (non-Javadoc)
	 * @see br.com.j7.jdesk.persistence.repository.impl.AbstractRepository#list()
	 */
	@Override
	public List<Enterprises> list() throws RepositoryException {
		try {
			return listByNamedQuery(Enterprises.class, "enterprise");
		} catch (RepositoryException e) {
			throw new RepositoryException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see br.com.j7.jdesk.persistence.repository.EnterpriseRepository#findByEnterprise(java.lang.String)
	 */
	@Override
	public Enterprises findByEnterprise(String cdEnterprise) throws RepositoryException {
		try {
			return getEntity(Enterprises.class, "enterpriseByCdEnterprise", cdEnterprise);
		} catch (RepositoryException e) {
			throw new RepositoryException(e);
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see br.com.j7.jdesk.persistence.repository.impl.AbstractRepository#find(java.lang.Integer)
	 */
	@Override
	public Enterprises find(Integer id) throws RepositoryException {
		try {
			return getEntity(Enterprises.class, id);
		} catch (RepositoryException e) {
			throw new RepositoryException(e);
		}
	}
	
	/*
	 * (non-Javadoc)
	 * @see br.com.j7.jdesk.persistence.repository.EnterpriseRepository#addEnterprise(br.com.j7.jdesk.persistence.entity.Enterprises, br.com.j7.jdesk.persistence.entity.UsersGroups, br.com.j7.jdesk.persistence.entity.Users)
	 */
	@Override
	public Enterprises addEnterprise(Enterprises enterprise, UsersGroups userGroup, Users user) throws RepositoryException {
		try {
			beginManager();
			
			if( enterprise.getIdEnterprise() == null ){
				getManager().persist( enterprise );
				getManager().persist( userGroup );
				getManager().persist( user );
			}else {
				enterprise = getManager().merge( enterprise );
			}
			closeManager();
			return enterprise;			  
		} catch (Exception e) {
			rollBackManager();
			throw new RepositoryException(e);
		}
	}

}
